package com.evan.wj.controller;

import com.evan.wj.pojo.User;
import com.evan.wj.result.Result;
import com.evan.wj.result.ResultFactory;
import com.evan.wj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping ("/api/users")
    public List<User> all(){
        return userService.all();
    }

    @PostMapping("/api/user")
    public User get(@RequestBody User user){
        System.out.println("----1231-----");
        System.out.println(user);
        return userService.getByName(user.getUsername());
    }

    @PostMapping("/api/editUser")
    public Result edit(@RequestBody User user){
        System.out.println(user+"-------------");
        userService.add(user);
        return ResultFactory.buildSuccessResult(null);
    }

    @PostMapping("/api/users/search")
    public Result search(@RequestBody User user){
        if ("".equals(user.getUsername())) {
            List<User> all = userService.all();
            if (all.size()> 0)
                return ResultFactory.buildSuccessResult(all);
        } else {
            List<User> allByName = userService.getAllByName(user.getUsername());
            return ResultFactory.buildSuccessResult(allByName);
        }
        return ResultFactory.buildFailResult("发生错误联系开发人员");
    }

    @PostMapping("/api/user/delete")
    public Result delete(@RequestBody User user){
        System.out.println(user+"-------------");
        userService.delete(user);
        return ResultFactory.buildSuccessResult(null);
    }
}
